//-------------------------------------------------------
// Header Files
//-------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

//-------------------------------------------------------
// Constants
//-------------------------------------------------------
//maximum possible number of fields that will used to store in the outfile
#define MAXKEY 39 
#define MAXVALUE 7

//#define readfile T30720140203041301.csv
//#define outfile workload2.txt

#define ERR_UNKNOWN 7

void parse(char *record, char *delim, char *key,char *value);

void parse(char *record, char *delim, char* key,char *value){
   	char*p = strtok(record,delim);
	//counter for column. This will be used to select the specific columns of the csv file	
	int colcounter=1;
	//taking care of when there isn't any valid keys or values in the file
	if(p==NULL){
		perror("No keys/values to be read in the file");
		exit(ERR_UNKNOWN);
	}	
	//gets the first(key) and fourth(value) of the csv file
    	while(p)
    	{	
		if(colcounter==2){
    			strcpy(key,p);
 		}		
		if(colcounter>2){
			if(isdigit(p[0])){
				strcpy(value,p);
				break;
			}
		}
    		p=strtok(NULL,delim);
		colcounter++;

   	 }
}
/**
* Main function to handle the whole mechanism to parse the csv file
*/
int main(int argc, char *argv[])
{
	char tmp[1024];
    	char key[MAXKEY];
	char value[MAXVALUE];
	//used to discard memos underneath the data table in the csv file	
	int numdata=1;

    	FILE *in=fopen("T30720140203041301.CSV","r"); //open file to read
	FILE *out=fopen("workload2.txt","a");//open file to write
		
	//checks if the 'readfile' doesn't exist 
    	if(in==NULL)
   	{
   		perror("File open error");
    		exit(ERR_UNKNOWN);
    	}	
	
	//prints out the label of the table
	fprintf(out,"%39s%7s\n","Key","Value");
	
	//checks if there is arguments inside the file 
	if(fgets(tmp,sizeof(tmp),in)==0)
	{
		perror("No arguments to be read in the file");
		exit(ERR_UNKNOWN);
	}
	
	//used to ignore the first line in the csv file, which is the label of the table in the file
	//fgets(tmp,sizeof(tmp),in);
	
	//parses the csv file
   	while((fgets(tmp,sizeof(tmp),in)!=0)&&(numdata<=692))
    	{
		//gets each line of first and fourth column in a char array 
    		parse(tmp,",",key,value);     		
		//prints each line into the outfile 
    		fprintf(out,"%39s%7s\n",key,value);
		numdata++;
    	}
    	fclose(in);
	fclose(out);
    	return 0;	
}
